<?php
namespace Application\Api\Controller;

class SystemTask extends Base
{

    /*
        /Api/SystemTask/weiXinSpOrderCheck
    */
    public function weiXinSpOrderCheckAction()
    {
        $requestData = $this->getRequestData();
        if(notSetOrEmpty($requestData, 'orderNo')){
            $this->sendFail();
            return false;
        }
        $orderNo = $requestData['orderNo'];
        $serviceOrder = $this->get(SERVICE_ORDER);
        $order = $serviceOrder->getByOrderNo($orderNo);
        if(empty($order)){
            $this->sendFail();
            return false;
        }
        if($order->dry_status == ORDER_STATUS_PAY){
            $this->sendSuccess();
            return false;
        }
        $payWeiXinSp = $this->get(PAY_WEIXINSP);
        $data = $payWeiXinSp->queryPay($orderNo);
        if(setAndNotEmpty($data, 'return_code') && $data['return_code'] == 'SUCCESS' && $data['trade_state'] == 'SUCCESS'){
            $update = [
                'dry_status' => ORDER_STATUS_PAY,
                'dry_pay_raw' => json_encode_plus($data)
            ];
            $serviceOrder->update($update, $order->id);
            $this->paySuccess($order);
            $this->addIncome($order);
            $this->sendSuccess();
            return false;
        }
        $this->sendFail();
        return false;
    }

    /*
        /Api/SystemTask/weiXinSpOrderCancel
    */
    public function weiXinSpOrderCancelAction()
    {
        $requestData = $this->getRequestData();
        if(notSetOrEmpty($requestData, 'orderNo')){
            $this->sendFail();
            return false;
        }
        $orderNo = $requestData['orderNo'];
        $serviceOrder = $this->get(SERVICE_ORDER);
        $order = $serviceOrder->getByOrderNo($orderNo);
        if(empty($order)){
            $this->sendFail();
            return false;
        }
        if(in_array($order->dry_status, [ORDER_STATUS_PAY, ORDER_STATUS_CANCEL, ORDER_STATUS_FINISH])){
            $this->sendSuccess();
            return false;
        }
        if($order->dry_status == ORDER_STATUS_NO_PAY && isPayTimeout($order->dry_add_time)){
            $update = [
                'dry_status' => ORDER_STATUS_CANCEL
            ];
            $serviceOrder->update($update, $order->id);
            $this->sendSuccess();
            return false;
        }
        else{
            $this->sendFail();
            return false;
        }
    }

    /*
        /Api/SystemTask/income2account
    */
    public function income2accountAction()
    {
        $requestData = $this->getRequestData();
        if(notSetOrEmpty($requestData, 'orderNo')){
            $this->sendFail();
            return false;
        }
        $orderNo = $requestData['orderNo'];
        $serviceOrder = $this->get(SERVICE_ORDER);
        $order = $serviceOrder->getByOrderNo($orderNo);
        if(empty($order)){
            $this->sendFail();
            return false;
        }
        $serviceUserIncomeLog = $this->get(SERVICE_USERINCOMELOG);
        $incomeLog = $serviceUserIncomeLog->getByOrderNo($orderNo);
        if(empty($incomeLog)){
            $this->sendFail();
            return false;
        }
        if(in_array($order->dry_status, [ORDER_STATUS_PAY, ORDER_STATUS_FINISH]) && $incomeLog->dry_amount < $order->dry_amount){
            $serviceUserAccount = $this->get(SERVICE_USERACCOUNT);
            $userId = $incomeLog->dry_user;
            $addOrSub = ACCOUNT_ADD;
            $type = ACCOUNT_LOG_TYPE_SALE_INCOME;
            $amount = $incomeLog->dry_amount;
            $note = '收益转余额';
            $more = [];
            $serviceUserAccount->addAccount($userId, $addOrSub, $type, $amount, $note, $more);
            $this->sendSuccess();
            return false;
        }
        else{
            $this->sendSuccess();
            return false;
        }
    }

    /*
        支付成功
    */
    private function paySuccess($order)
    {
        $product = json_decode($order->dry_product_raw, false);
        $userId = $order->dry_user;
        $mainProduct = $product->dry_main_product;
        $mainProductSpec = $product->dry_main_product_spec;
        if(in_array($mainProductSpec, getProductAgentMainProductSpec())){
            $serviceProductAgent = $this->get(SERVICE_PRODUCTAGENT);
            $agent = $serviceProductAgent->hasAgent($userId, $mainProduct, $mainProductSpec);
            if(empty($agent)){
                $startTime = $order->dry_add_time;
                $endTime = THE_DATE_TIME_END_LONG;
                $serviceProductAgent->addAgent($userId, $mainProduct, $mainProductSpec, $startTime, $endTime);
            }
        }
    }

    /*
        支付成功添加收益
    */
    private function addIncome($order)
    {
        $product = json_decode($order->dry_product_raw, false);
        if(isset($product->codeUserId)){
            $codeUserId = $product->codeUserId;
            $orderNo = $order->dry_order_no;
            $orderAmount = $order->dry_amount;
            $serviceUserIncomeLog = $this->get(SERVICE_USERINCOMELOG);
            $serviceProductAgent = $this->get(SERVICE_PRODUCTAGENT);
            $userIncomeLog = $serviceUserIncomeLog->hasIncome($codeUserId, $orderNo);
            if(!$userIncomeLog && $orderAmount > 0){
                $mainProduct = $product->dry_main_product;
                $productAgent = $serviceProductAgent->getCurrentAgent($codeUserId, $mainProduct, $order->dry_add_time);
                $mainProductSpec = $productAgent->dry_main_product_spec;
                $rate = getProductAgentRate($mainProduct, $mainProductSpec);
                if($rate > 0 && $rate < 1){
                    $amount = bcmul($orderAmount, $rate, 2);
                    $more = [
                        'orderNo' => $orderNo
                    ];
                    $serviceUserIncomeLog->addIncome($codeUserId, ACCOUNT_ADD, ACCOUNT_LOG_TYPE_SYSTEM_ADD, $amount, '自动发放', $more);
                    $this->income2account($order);
                }
            }
        }
    }

    /*
        收益7天后转入余额
    */
    private function income2account($order)
    {
        $domain = getDomain();
        $theData = [
            'order_no' => $order->dry_order_no
        ];
        /*任务入库 start*/
        $startTime = getDateTimeStd(getTimestamp() + WEEK_SECOND);
        $endTime = getDateTimeStd(getTimestamp() + WEEK_SECOND + 7200);
        $this->get(SERVICE_SYSTEMTASK)->addTask('income2account', "{$domain}/Api/SystemTask/income2account", 0, 10, $startTime, $endTime, 300, json_encode($theData));
        /*任务入库 end*/
    }

}